<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="hOut">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />

          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
          >
            <template #default="{row}">
              {{ hireTypeFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>

          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail?id=${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small" @click="hAssignRoles(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增弹层 -->
      <el-dialog
        title="新增"
        :visible.sync="showDialog"
        @close="hClose"
      >
        <empDialog ref="addRef" @success="hSuccess" @ZN="closeShowDialog" />
      </el-dialog>
      <!-- 分配角色弹层 -->
      <el-dialog
        title="分配角色"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialogRole"
      >
        <assign-role
          v-if="showDialogRole"
          :cur-id="curId"
          @close="showDialogRole=false"
        /></el-dialog>
    </div>
  </div>
</template>

<script>
import empDialog from './empDialog.vue'
import AssignRole from './assignRole'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
console.log('EmployeeEnum', EmployeeEnum.hireType)
const hireType = {}
EmployeeEnum.hireType.forEach(item => {
  hireType[item.id] = item.value
})
export default {
  components: {
    empDialog, AssignRole
  },
  data() {
    return {
      curId: '',
      showDialogRole: false, // 分配角色弹层默认关闭
      showDialog: false, // 新增弹层默认关闭
      list: [], // 获取员工列表
      page: 1, // 页码
      size: 2, // 每页显示的格式
      total: 0 // 总条数
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    hAssignRoles(id) {
      this.showDialogRole = true
      this.curId = id
    },
    // 导出
    formatData(list) {
      // 1. 根据数据对象的健根据映射关系，得到一个中文的健，放到一个数组中  ---header ['编号', '密码']
      // 2. 将每一个对象的值，存到一个数组中，所有的结果放入到一个大的数组中--data  [["2018-11-30", "总裁办"],[]]
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      const one = list[0]
      // 如果list中有数组，才需要生成表头
      if (!one) return // 没有数据 直接终止
      let headers = []
      headers = Object.keys(one).map(enkey => {
        console.log(' map[enkey]', map[enkey]) // 打印出来的是中文的表头
        return map[enkey]
      })

      // 2. 生成data数据
      const data = list.map(item => {
        return Object.values(item)
      })
      return { headers: headers, data: data }
    },

    // 导出数据
    async hOut() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log('getEmployeeList导出', res)
        const { headers, data } = this.formatData(res.data.rows)
        import('@/vendor/Export2Excel').then(excel => {
          // 3.调用excel.export_json_to_excel将格式好的数据写入Excel文件中
          excel.export_json_to_excel({
            header: headers,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
        // 保存数据
      } catch (err) {
        console.log('getEmployeeList', err)
      }
    },
    // 删除
    hDel(id) {
      this.$confirm('你确定要删除吗？')
        .then(async() => {
          const res = await delEmployee(id)
          console.log('删除', res)
          if (this.list.length === 1) {
            this.page--
          }
          this.loadEmployeeList()
        })
        .catch(err => console.log(err))
    },
    // 关闭弹窗
    closeShowDialog() {
      this.showDialog = false
    },
    hClose() {
      this.$refs.addRef.resetForm()
    },
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployeeList()
      this.showDialog = false
    },
    // 枚举
    hireTypeFormat(value) {
      return hireType[value] || '未知'
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.size = val
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeeList()
    },
    async loadEmployeeList() {
      const res = await getEmployeeList(this.page, this.size)
      this.list = res.data.rows
      this.total = res.data.total
      console.log('员工列表', res)
    }
  }
}
</script>
